package com.hyphenate.easeui.utils;


import com.hyphenate.easeui.EaseUI;
import com.hyphenate.easeui.domain.EaseUser;
import com.qf.dblib.dao.entity.ChatUser;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户信息控制类
 * 2020/2/24 21:18
 */
public class ChatUserCacheMgr implements EaseUI.EaseUserProfileProvider {
    private static volatile ChatUserCacheMgr instance = null;

    private ChatUserCacheMgr() {
    }

    public static ChatUserCacheMgr getInstance() {
        if (instance == null) {
            synchronized (ChatUserCacheMgr.class) {
                if (instance == null) {
                    instance = new ChatUserCacheMgr();
                }
            }
        }
        return instance;
    }

    /**
     * 保存用户信息
     */
    public boolean saveUser(ChatUser chatUser) {
        if (chatUser == null)
            return false;
        return chatUser.saveOrUpdate("uid = ?", chatUser.getUid());
    }

    public ChatUser find(String uid) {
        if (uid == null)
            uid = "";
        ChatUser chatUser = LitePal.where("uid = ?", uid).findLast(ChatUser.class);
        return chatUser == null ? new ChatUser() : chatUser;

    }



    /**
     * 获取所有登录过得用户
     */
    public List<ChatUser> getAllUser() {
        List<ChatUser> all = LitePal.findAll(ChatUser.class);
        if (all == null)
            return new ArrayList<>();
        return all;
    }


    @Override
    public EaseUser getUser(String username) {
        EaseUser easeUser = new EaseUser(username);
        ChatUser chatUser = find(username);
        easeUser.setNickname(chatUser.getNick());
        easeUser.setAvatar(chatUser.getAvatar());
        return easeUser;
    }
}